/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sysmo.server.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.sysmo.server.SysmoServer;
import org.sysmo.server.user.User;
import org.sysmo.server.user.UserNotExistsException;

/**
 *
 * @author Derek
 */
public class LoginForm extends org.apache.struts.action.ActionForm {
    
    private String username;

    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }


    /**
     *
     */
    public LoginForm() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param request The HTTP Request we are processing.
     * @return
     */
    @Override
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        if (username == null || username.length() < 1) {
            errors.add("username", new ActionMessage("login.emptyname"));
        }
        if (password == null || password.length() < 1) {
            errors.add("password", new ActionMessage("login.emptypassword"));
        }
        if (errors.isEmpty()) {
            SysmoServer server = (SysmoServer)getServlet().getServletContext().getAttribute("sysmoServer");
            try {
                User user = server.getUser(username);
                if (!user.verify(password)) {
                    errors.add("username/password", new ActionMessage("login.fail"));
                }
            } catch (UserNotExistsException e) {
                errors.add("username/password", new ActionMessage("login.fail"));
            }
        }
        if (!errors.isEmpty()) {
            password = "";
        }
        return errors;
    }
}
